package com.pro01.backend.mapper;

import com.pro01.backend.pojo.ShopOrder;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

@Mapper
public interface ShopOrderMapper {

    // 插入一条购买记录
    @Insert("""
    INSERT INTO shop_orders (
        user_id, item_id, item_name, points_spent, status, result_info
    ) VALUES (
        #{userId}, #{itemId}, #{itemName}, #{pointsSpent}, #{status}, #{resultInfo}
    )
""")
    int insertOrder(ShopOrder order);

    // 管理员审核晋升请求
    @Update("""
    UPDATE shop_orders
    SET status = #{status},
        result_info = #{resultInfo}
    WHERE id = #{orderId}
""")
    int updateOrderStatus(@Param("orderId") Long orderId,
                          @Param("status") String status,
                          @Param("resultInfo") String resultInfo);

    @Select("SELECT * FROM shop_orders WHERE id = #{orderId}")
    ShopOrder getOrderById(@Param("orderId") Long orderId);

    // 用户查看自己的兑换记录
    @Select("""
    SELECT * FROM shop_orders
    WHERE user_id = #{userId}
    ORDER BY created_at DESC
    LIMIT #{offset}, #{pageSize}
""")
    List<ShopOrder> getOrdersByUser(@Param("userId") Long userId,
                                    @Param("offset") int offset,
                                    @Param("pageSize") int pageSize);

    @Select("SELECT COUNT(*) FROM shop_orders WHERE user_id = #{userId}")
    int countOrdersByUser(@Param("userId") Long userId);

    /**
     * 下面是管理员接口
     */
    // 管理员查看所有兑换记录
    @Select("""
    SELECT o.*, u.username
    FROM shop_orders o
    LEFT JOIN users u ON o.user_id = u.id
    ORDER BY o.created_at DESC
    LIMIT #{offset}, #{pageSize}
""")
    List<Map<String, Object>> getAllOrdersPaged(@Param("offset") int offset,
                                                @Param("pageSize") int pageSize);

    @Select("SELECT COUNT(*) FROM shop_orders")
    int countAllOrders();

}
